using System;
using UnityEngine;
using UnityEngine.UI;

public static class UnityExtension
{
    public static void SetHide(this Transform transform)
    {
        transform.localScale = Vector3.zero;
    }

    public static void SetShow(this Transform transform)
    {
        transform.localScale = Vector3.one;
    }

    public static void SetHide(this GameObject gameObject)
    {
        SetHide(gameObject.transform);
    }

    public static void SetShowState(this Transform transform, bool state)
    {
        if (state)
        {
            transform.SetShow();
        }
        else
        {
            transform.SetHide();
        }
    }

    public static void SetShowState(this GameObject gameObject, bool state)
    {
        gameObject.transform.SetShowState(state);
    }


    public static void SetShow(this GameObject gameObject)
    {
        SetShow(gameObject.transform);
    }

    public static T GetCom<T>(this Transform transform, string fullPath = null) where T : Component
    {
        T ret;
        if (string.IsNullOrEmpty(fullPath))
        {
            ret = transform.GetComponent<T>();
        }
        else
        {
            ret = transform.Find(fullPath).GetComponent<T>();
            if (ret == null)
                Debug.LogError($"{transform.name} not {typeof(T).ToString()} component!");
        }
        return ret;
    }

    public static T GetCom<T>(this GameObject gameObject, string fullPath = null) where T : Component
    {
        return gameObject.transform.GetCom<T>(fullPath);
    }

    public static void BindEvent(this GameObject gameObject, Action action)
    {
        if (gameObject.GetCom<Button>() == null)
        {
            if (gameObject.GetComponent<Image>() == null && gameObject.GetComponent<EmptyRaycast>() == null)
            {
                gameObject.AddComponent<EmptyRaycast>();
            }
            gameObject.AddComponent<Button>();
        }
        gameObject.GetCom<Button>().BindEvent(action);
    }

    public static void BindEvent(this Transform transform, Action action)
    {
        transform.gameObject.BindEvent(action);
    }

    public static void BindEvent(this Button button, Action action)
    {
        if (button != null)
        {
            button.onClick.AddListener(() =>
            {
                Global.AudioMgrIns.PlayEffectAudio("Common_A/BT1");
                action?.Invoke();
            });
        }
        else
        {
            throw new NullReferenceException("BindEvent button is null");
        }
    }
}
